package com.example.mydatasingleservice;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Intent;
import android.util.Log;

import com.example.mydatasingleservice.services.AService;
import com.example.mydatasingleservice.services.BService;
import com.example.mydatasingleservice.services.CService;

import java.util.List;

public class MApplication  extends Application {
    private static final String TAG = "MApplication";
    private static  MApplication mApplication;
    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
    }
    public static void startAservice(){
        if(!isServiceRunning(AService.class.getName())) {
            Log.d(TAG, "startAservice: ");
            mApplication.startService(new Intent(mApplication, AService.class));
        }
    }
    public static void startBservice(){
        if(!isServiceRunning(BService.class.getName())) {
            Log.d(TAG, "startBservice: ");
            mApplication.startService(new Intent(mApplication, BService.class));
        }
    }
    public static void startCservice(){
        if(!isServiceRunning(CService.class.getName())) {
            Log.d(TAG, "startCservice: ");
            mApplication.startService(new Intent(mApplication, CService.class));
        }
    }
    public static Boolean isServiceRunning(String className){
        ActivityManager activityManager = (ActivityManager) mApplication.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> list = activityManager.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).service.getClassName().equals(className)){
                Log.d(TAG, "isServiceRunning: 服务已开启"+className);
                return true;
            }
        }
        Log.d(TAG, "isServiceRunning: 服务未开启");
        return false;
    }

}
